package com.leapp.sk.viewdelegate.classs

import android.content.Intent
import android.support.v7.app.AppCompatActivity
import android.support.v7.widget.LinearLayoutManager
import android.support.v7.widget.RecyclerView
import android.text.Editable
import android.text.TextUtils
import android.text.TextWatcher
import android.view.View
import android.widget.ImageView
import com.example.baselibrary.db.dao.AccountDao
import com.example.baselibrary.db.table.AccountTable
import com.example.inter.ItemClickInterface
import com.example.mvp.delegate.BaseAppDelegate
import com.example.mvp.view.ContainsEmojiEditText
import com.example.mvp.view.SKTopBar
import com.example.mvp.view.slidebar.IndexBar
import com.example.mvp.view.slidebar.IndexLayout
import com.example.mvp.view.slidebar.NormalDecoration
import com.example.mvp.view.slidebar.RecCarAdapter
import com.leapp.sk.R
import com.leapp.sk.ui.activity.classs.ClassMemberActivity
import com.example.mvp.view.slidebar.util.PinyinComparator
import com.example.mvp.view.slidebar.util.CharacterParser
import com.leapp.sk.app.SKApplication
import com.example.mvp.bean.ClassMemberInfoEntity
import com.leapp.sk.ui.activity.classs.HeadmasterDetialActivity
import com.example.util.finallist.THEACHER_DATA
import java.util.*
import kotlin.collections.ArrayList


/**
 * 班级成员视图托管类
 * @author  chaohaipeng  on 2018/7/31.
 */
class ClassMemberDelegate : BaseAppDelegate(), ItemClickInterface {

    /**
     * 数据源
     */
    private var SourceDateList = mutableListOf<ClassMemberInfoEntity>()
    /**
     * 搜索时德的数据
     */
    var filterDateList = mutableListOf<ClassMemberInfoEntity>()
    /**
     * 汉字转拼音
     */
    private var characterParser: CharacterParser? = null
    /**
     *适配器
     */
    private var mAdapter: RecCarAdapter? = null
    /**
     *搜索适配器
     */
    private var mSearchAdapter: RecCarAdapter? = null


    /**
     *排序
     */
    private var pinyinComparator: PinyinComparator? = null

    /**
     *列表
     */
    private var rv_acm_list: RecyclerView? = null

    /**
     *搜索列表
     */
    private var rv_acm_search_list: RecyclerView? = null

    override fun initWidget() {
    }

    override fun initLayoutRes(): Int {
        return R.layout.activity_class_member
    }
    override fun itemClick(position: Int) {
        try {
            val intent=Intent(getActivity<AppCompatActivity>(),HeadmasterDetialActivity::class.java)
            if (rv_acm_search_list?.visibility==View.VISIBLE){
                if (filterDateList.size>0){
                    val get = filterDateList.get(position)
                    intent.putExtra(THEACHER_DATA, get)
                }
            }else{
                val get = SourceDateList.get(position)
                intent.putExtra(THEACHER_DATA,get)
            }
            getActivity<AppCompatActivity>().startActivity(intent)
        }catch (e:Exception){
        }
    }

    /***
     * 初始化适配器
     */
    fun initAdapter(datas:List<ClassMemberInfoEntity>?) {

        rv_acm_list = getView<RecyclerView>(R.id.rv_acm_list)
        //实例化汉字转拼音类
        characterParser = CharacterParser.getInstance()
        pinyinComparator = PinyinComparator()
        if (datas == null||datas.size==0) {
            return
        }
            for (data in datas) {
                filledData(data)
                val accountTable = AccountTable()
                accountTable.avatar=data?.avatar
                accountTable.nick=data?.nickName
                accountTable.account=data?.phone
                AccountDao.getInstance().createOrUpdate(accountTable)
            }

        if (SourceDateList.size > 0) {
            // 根据a-z进行排序源数据
            Collections.sort(SourceDateList, pinyinComparator)
        }
        mAdapter = RecCarAdapter(getActivity())
        mAdapter?.setItemClickInterface(this)
        mAdapter?.addDatas(SourceDateList)
       val decoration = object : NormalDecoration() {
            override fun getHeaderName(pos: Int): String? {
                if (SourceDateList.size>0) {
                    val sortLetters = SourceDateList.get(pos).sortLetters
                    if (TextUtils.isEmpty(sortLetters)){
                        return sortLetters
                    }else{
                        return ""
                    }

                } else {
                    return ""
                }
            }
        }

        val manager = LinearLayoutManager(getActivity())
        rv_acm_list?.addItemDecoration(decoration)
        rv_acm_list?.layoutManager = manager
        rv_acm_list?.adapter = mAdapter
        //侧边导航栏
        val indexLayout = getView<IndexLayout>(R.id.il_acm_index)
        val heads = ArrayList<String>()

        if (SourceDateList.size>0) {
            for (car in SourceDateList) {
                if (!heads.contains(car.sortLetters)) {
                    val sortLetters = car.sortLetters
                    if (sortLetters!=null){
                        heads.add(sortLetters)
                    }

                }
            }
        }
        indexLayout.setIndexBarHeightRatio(0.9f)
        indexLayout.getIndexBar().setIndexsList(heads)
        indexLayout.getIndexBar().setIndexChangeListener(object : IndexBar.IndexChangeListener {
            override fun indexChanged(indexName: String) {
                if (SourceDateList != null) {
                    for (i in SourceDateList.indices) {
                        if (indexName == SourceDateList.get(i).sortLetters) {
                            manager.scrollToPositionWithOffset(i, 0)
                            return
                        }
                    }
                }
            }
        })
        initEvent()
        initSearchAdapter()
    }

    /**
     * 初始化搜索时的适配器
     */
   fun  initSearchAdapter(){
        rv_acm_search_list = getView<RecyclerView>(R.id.rv_acm_search_list)
        mSearchAdapter = RecCarAdapter(getActivity())
        val manager = LinearLayoutManager(getActivity())
        rv_acm_search_list?.layoutManager = manager
        rv_acm_search_list?.adapter = mSearchAdapter

   }




    /**
     * 初始化事件
     */
    private fun initEvent() {
        val iv_acm_clear = getView<ImageView>(R.id.iv_acm_clear)
        val et_acm_search_content = getView<ContainsEmojiEditText>(R.id.et_acm_search_content)
        et_acm_search_content.addTextChangedListener(object : TextWatcher {
            override fun afterTextChanged(p0: Editable?) {

                val compareTo = p0?.length!!.compareTo(0)
                if (compareTo == 0) {
                    iv_acm_clear.visibility = View.INVISIBLE
                    rv_acm_search_list?.visibility=View.GONE
                    rv_acm_list?.visibility=View.VISIBLE
                } else {
                    iv_acm_clear.visibility = View.VISIBLE
                    rv_acm_list?.visibility=View.GONE
                }

                if (p0!=null&&!TextUtils.isEmpty(p0.toString())){
                    SKApplication.getInstance()?.mHandler?.postDelayed(object : Runnable {
                        override fun run() {
                            edtfilterData(p0.toString())
                        }

                    }, 1000)
                }
            }

            override fun onTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {
            }

            override fun beforeTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {




            }

        })
    }

    /**
     * 清理内容
     */
    fun clearContent() {
        val et_acm_search_content = getView<ContainsEmojiEditText>(R.id.et_acm_search_content)
        et_acm_search_content.setText("")
    }

    /**
     * 设置标题栏
     */
    fun setTitle(title: String?) {
        if (!TextUtils.isEmpty(title)) {
            val jtb_acm = getView<SKTopBar>(R.id.jtb_acm)
            jtb_acm.setTitle(title)
        }
        setEvent()
    }

    /**
     * 设置设置事件
     */
    private fun setEvent() {
        val jtb_acm = getView<SKTopBar>(R.id.jtb_acm)
        jtb_acm.inVisibleLine()
        jtb_acm?.setEventInterface(object : SKTopBar.EventInterface {
            override fun leftOnClick() {
                getActivity<ClassMemberActivity>().finish()
            }

            override fun rightOnClick() {
            }

        })
    }

    /**
     * 为ListView填充数据
     * @param date
     * @return
     */
    private fun filledData(data: ClassMemberInfoEntity) {
        val sortModel = ClassMemberInfoEntity()
        val nickName = data.nickName
        sortModel.nickName = nickName
        sortModel.avatar=data.avatar
        sortModel.id=data.id
        sortModel.phone=data.phone
        sortModel.personnelType=data.personnelType
        //汉字转换成拼音
        val pinyin = characterParser?.getSelling(nickName)
        val sortString = pinyin?.substring(0, 1)?.toUpperCase()

        // 正则表达式，判断首字母是否是英文字母
        val matches = sortString?.matches("[A-Z]".toRegex())
        if (matches != null) {
            if (matches) {
                sortModel.sortLetters = sortString?.toUpperCase()
            }
        }
        SourceDateList.add(sortModel)

    }

    /**
     * 根据输入框中的值来过滤数据并更新ListView
     * @param filterStr
     */
    private fun edtfilterData(filterStr: String) {
        if (TextUtils.isEmpty(filterStr)) {
        } else {
            filterDateList.clear()
            for (sortModel in SourceDateList) {
                val name = sortModel.nickName
                val startsWith = characterParser?.getSelling(name)?.toUpperCase()?.startsWith(filterStr.toString().toUpperCase())
                if (startsWith != null) {
                    if (name?.toUpperCase()?.indexOf(filterStr.toString().toUpperCase()) != -1 || startsWith) {
                        filterDateList.add(sortModel)
                    }
                }

            }
            Collections.sort(filterDateList, pinyinComparator)
                mSearchAdapter?.addDatas(filterDateList)
            rv_acm_search_list?.visibility=View.VISIBLE
//            if (filterDateList.size > 0) {
//                Collections.sort(filterDateList, pinyinComparator)
//                mAdapter?.addDatas(filterDateList)
//
//                decorationFilter = object : NormalDecoration() {
//                    override fun getHeaderName(pos: Int): String {
//                        return filterDateList.get(pos).sortLetters
//                    }
//                }
//                rv_acm_list?.addItemDecoration(decorationFilter)
//            }
        }



    }


}